<template>
  <div class="app-container">
    <vue-element-loading
      :active="this.$store.state.elementloading.vueElementLoading"
      spinner="spinner"
      color="#FF6700"
    />
    <el-card shadow="never">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchMap"
        style="margin-top: 20px;margin-left: 0px"
      >
        <el-form-item prop="companyName">
          <el-input @keyup.enter.native="searchMedicinalGone" v-model.lazy="searchMap.gName">
            <template slot="prepend">原料去向</template>
          </el-input>
        </el-form-item>
        <el-button @click="searchMedicinalGone" icon="el-icon-search"></el-button>
      </el-form>

      <el-button-group style="margin-bottom:20px">
        <el-button v-if="btnshow('medicinalgone-add')" @click="openNew" size="small" type="primary" icon="el-icon-plus"></el-button>
        <el-button v-if="btnshow('medicinalgone-update')" @click="handleEdit(radio)" size="small" type="primary" icon="el-icon-edit"></el-button>
        <el-button v-if="btnshow('medicinalgone-delete')" @click="deleteCompany(radio)" size="small" type="primary" icon="el-icon-delete"></el-button>
      </el-button-group>
      <template>
        <el-table
          :data="list"
          max-height="500"
          border
          style="width: 100%"
          @row-click="chooseone"
          highlight-current-row
          @current-change="handleSelectionChange"
        >
          <el-table-column width="55">
            <template slot-scope="scope">
              <el-radio v-model="radio" :label="scope.row.id">
                <span class="el-radio__label"></span>
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="gName" label="原料去向"></el-table-column>
          <el-table-column prop="gMedicinalGoneSale" label="销量（Kg/年）"></el-table-column>
          <el-table-column prop="gMedicinalGoneProportion" label="占总产量比例（%）"></el-table-column>
          <el-table-column prop="gMedicinalGonePrice" label="价格" align="center"></el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 编辑原料去向弹窗 -->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        v-dialogDrag
        :title="title"
        :visible.sync="editdataDialog"
        width="40%"
      >
        <el-form
          :rules="rules"
          ref="editForm"
          :model="pojo"
          label-width="135px"
          label-position="right"
        >
          <el-form-item label="原料去向：" prop="gName">
            <!-- autocomplete="off"为 保存之前填过的值 -->
            <el-input v-model="pojo.gName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="销量(kg/年)：" prop="gMedicinalGoneSale">
            <el-input v-model="pojo.gMedicinalGoneSale" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="占总产量比例(%)：" prop="gMedicinalGoneProportion">
            <el-input v-model="pojo.gMedicinalGoneProportion" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="价格：" prop="gMedicinalGonePrice">
            <el-input v-model="pojo.gMedicinalGonePrice" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleData">取 消</el-button>
          <el-button @click="addData" type="primary">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <router-view />
  </div>
</template>

<script>
import medicinalgoneApi from "@/api/medicinalgone";
import VueElementLoading from "vue-element-loading";
import { hasPermissionPoint } from "@/utils/permission";

export default {
  components: {
    VueElementLoading
  },
  data() {
    return {
      pojo: {
        id: "",
        gName: "",
        gMedicinalId: "",
        gProductbaseId: "",
        gMedicinalGoneSale: "",
        gMedicinalGoneProportion: "",
        gMedicinalGonePrice: ""
      },
      searchMap: {
        medicinalId: "",
        productbaseId: "",
        gName: "",
        page: "",
        size: ""
      },
      backup: {},
      list: [],
      total: 0, //总记录数
      currentPage: 1, //当前页码
      pageSize: 5, //每页显示10条数据
      radio: null, // 如果使用单选框，定义一个model值
      currentSelectItem: {}, //当前选中的值
      editdataDialog: false,
      rules: {
        // 校验规则
        gName: [
          { required: true, message: "原料去向不能为空", trigger: "blur" }
        ]
      },
      title: ""
    };
  },

  created() {
    // 初始化获取列表数据
    console.log("当前路径：", this.$route);
    this.searchMedicinalGone();
  },

  watch: {
    // 监听相同路由下参数变化的时候，从而实现异步刷新
    // 实时监听路由变化是因为在AppMain中去除了include，页面被缓存，不能自动刷新
    $route(to, from) {
      // 做一些路由变化的响应
      this.searchMedicinalGone();
    }
  },

  methods: {
    btnshow(point) {
      return hasPermissionPoint(point);
    },
    chooseone(row) {
      // console.log("当前行：",row)
      this.radio = row.id;
      this.backup = this.pojo = row;
    },
    handleSelectionChange(row) {
      console.log(row);
      this.currentSelectItem = row;
    },
    // 当每页显示条数改变后，被触发，val是最新的显示条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.searchMedicinalGone();
    },
    // 当页码改变后，被触发，val是最新的页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.searchMedicinalGone();
    },
    searchcompany() {
      this.currentPage = 1;
      this.searchMedicinalGone();
    },
    // 根据原料去向查询
    searchMedicinalGone() {
      var vm = this.$store;
      vm.commit("updateLoading", true);
      console.log(
        "是否开启加载",
        this.$store.state.elementloading.vueElementLoading
      );
      this.searchMap.medicinalId = localStorage.getItem("tMedicinalId");
      this.searchMap.productbaseId = localStorage.getItem("tProductBaseId");
      this.searchMap.page = this.currentPage;
      this.searchMap.size = this.pageSize;
      medicinalgoneApi.select(this.searchMap).then(resp => {
        this.list = resp.data.rows;
        this.total = resp.data.total;
        if (resp.data.rows) {
          vm.commit("updateLoading", false);
          console.log(
            "是否开启加载",
            this.$store.state.elementloading.vueElementLoading
          );
        }
        console.log("原料去向", resp.data.rows);
      });
    },
    // 打开新增弹窗
    openNew() {
      this.isEdit = false;
      this.openDialog(this.isEdit);
    },
    // 打开修改弹窗
    handleEdit(id) {
      if (id != null && id != "") {
        this.isEdit = true; // 切换为修改状态
        this.openDialog(this.isEdit);
        // this.fpojo
      } else {
        this.$message({
          message: "请选择需要修改的原料去向哦！",
          type: "warning"
        });
      }
    },

    handleDialogClose() {
      this.editdataDialog = false;
    },

    // 关闭编辑弹窗，并将值赋为空
    closeDialog() {
      this.editdataDialog = false;
      this.pojo = {
        id: "",
        gMedicinalId: "",
        gProductbaseId: "",
        gName: "",
        gMedicinalGoneSale: "",
        gMedicinalGoneProportion: "",
        gMedicinalGonePrice: ""
      };
      this.searchMedicinalGone();
    },

    // 打开弹窗
    openDialog(e) {
      if (e) {
        this.pojo = this.backup;
        // console.log("要修改的内容：",this.pojo);
        this.title = "修改原料去向";
      } else {
        this.title = "新增原料去向";
        this.pojo = {
          id: "",
          gName: "",
          gMedicinalGoneSale: "",
          gMedicinalGoneProportion: "",
          gMedicinalGonePrice: ""
        };
      }
      this.editdataDialog = true;
      // 请求校验规则
      this.$nextTick(() => {
        this.$refs["editForm"].clearValidate();
      });
    },

    // 取消上传表单
    cancleData() {
      this.closeDialog();
    },

    // 提交表单
    addData() {
      this.pojo.gMedicinalId = localStorage.getItem("tMedicinalId");
      this.pojo.gProductbaseId = localStorage.getItem("tProductBaseId");
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            // 修改
            medicinalgoneApi.update(this.pojo).then(resp => {
              if (resp.data.code == 0) {
                //修改成功
                this.$message({
                  message: "修改原料去向成功",
                  type: "success"
                });
                // 关闭
                this.closeDialog();
                // 刷新数据
              } else {
                // 失败
                this.$message({
                  message: "修改原料去向失败",
                  type: "warning"
                });
              }
            });
          } else {
            medicinalgoneApi.insert(this.pojo).then(resp => {
              if (resp.data.code == 0) {
                //新增成功
                this.$message({
                  message: "新增原料去向成功",
                  type: "success"
                });
                // 关闭
                this.closeDialog();
              } else {
                // 失败
                this.$message({
                  message: "新增原料去向失败",
                  type: "warning"
                });
              }
            });
          }
        } else {
          this.$message({
            message: "提交表单失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    // 删除公司
    deleteCompany(id) {
      if (id != null && id != "") {
        this.$confirm("此操作将永久删除该原料去向, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            medicinalgoneApi.delete(id).then(resp => {
              if (resp.data.code == 0) {
                this.$message({
                  message: "删除原料去向信息成功",
                  type: "success"
                });
                this.searchMedicinalGone();
                this.radio = "";
              } else {
                this.$message({
                  message: "删除原料去向信息失败",
                  type: "warning"
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.$message({
          message: "请选择需要删除的原料去向哦！",
          type: "warning"
        });
      }
    }
  }
};
</script>

<style lang="css" >
.el-dialog {
  max-height: calc(100% - 200px);
  /* max-height: 600px; */
  display: flex;
  flex-direction: column;
}
.el-dialog__body {
  overflow: auto;
}
</style>

<style lang="css" scoped>
.el-radio__label {
  display: none;
}
/* body .el-table th.gutter {
  display: table-cell !important;
} */
/* .el-table >>> th {
  background-color: #eee;
} */
.el-table >>> td {
  font-size: 13px;
}
</style>